package imu.ming.spring.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * IP地址工具类
 * @Author Zhangxiliang
 * @Date 2020/5/30
 */
public class IpUtil {

  private static final String LOOPBACK_ADDRESS = "127.0.0.1";
  private static final String IPV6_ADDRESS = "0:0:0:0:0:0:0:1";

  public static String getIpAddr(HttpServletRequest request) {
    try {
      String ip = request.getHeader("x-forwarded-for");
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
      }
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
      }
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
      }
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
      }
      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
      }
      if (IPV6_ADDRESS.equals(ip)) {
        ip = LOOPBACK_ADDRESS;
      }
      return ip;
    } catch (Exception e) {
      System.out.println("获取IP地址异常：" + e.getMessage());
    }
    return "";
  }
}
